package com.xuecheng.media.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.base.utils.StringUtil;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.mapper.MediaStatusMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.MediaStatus;
import com.xuecheng.media.service.MediaFileService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/9/10 8:58
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MediaFileServiceImpl implements MediaFileService {

    private final MediaFilesMapper mediaFilesMapper;
    private final MinioClient minioClient;
    private final MediaStatusMapper mediaStatusMapper;
    private final MediaProcessMapper mediaProcessMapper;
    @Autowired
    private MediaFileService mediaFileService;
    @Value("${minio.bucket.files}")
    private String mediafiles;
    @Value("${minio.bucket.videofiles}")
    private String videofiles;


    /**
     * 分页查询文件
     *
     * @param companyId
     * @param pageParams          分页参数
     * @param queryMediaParamsDto 查询条件
     * @return
     */
    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    /**
     * 上传文件
     *
     * @param companyId
     * @param uploadFileParamsDto
     * @param localFilePath
     * @return
     */
    @Override
    public UploadFileResultDto upload(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath, String objectName) {
        File file = new File(localFilePath);
        if (!file.exists()) {
            XueChengPlusException.cast("文件不存在");
        }

        //文件名
        String fileName = uploadFileParamsDto.getFilename();

        //获取文件后缀
        String extension = fileName.substring(fileName.lastIndexOf('.') + 1);

        //获取文件类型
        String mimeType = getFileType(extension);

        //获取md5
        String md5Str = getMd5Str(localFilePath);

        //生成objectName
        if (StringUtils.isEmpty(objectName)) {
            objectName = getObjectName(md5Str, extension);
        }
        //bucket
        String bucket = mediafiles;

        //上传文件
        boolean b = addMediaFilesToMinIO(bucket, localFilePath, mimeType, objectName);
        if (!b) {
            return null;
        }

        //校验文件完整性,下载文件,获取文件的md5
        boolean b1 = downloadFile(bucket, md5Str, objectName);
        if (!b1) {
            log.error("文件校验失败,桶:{},路径:{}", bucket, objectName);
            return null;
        }

        //文件大小
        uploadFileParamsDto.setFileSize(file.length());

//       删除临时文件
        boolean b2 = file.delete();
        if (!b2) {
            log.error("删除临时文件失败");
        }

        //将文件信息存入数据库,这里是为了事务处理生效
        MediaFiles mediaFiles = mediaFileService.AddMediaFileInfo(uploadFileParamsDto, companyId, bucket, md5Str, objectName);

        UploadFileResultDto uploadFileResultDto = BeanUtil.copyProperties(mediaFiles, UploadFileResultDto.class);

        return uploadFileResultDto;
    }

    /**
     * 下载并校验文件
     *
     * @param bucket
     * @param md5Str
     * @param objectName
     * @return
     */
    private boolean downloadFile(String bucket, String md5Str, String objectName) {
        //组装下载参数
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucket)
                .object(objectName)
                .build();
        try (GetObjectResponse response = minioClient.getObject(getObjectArgs)) {
            String md5Hex = DigestUtils.md5Hex(response);
            if (!md5Str.equals(md5Hex)) {
                log.error("文件校验失败,桶:{},文件路径:{}", bucket, objectName);
                return false;
            } else {
                log.info("文件完整,桶:{},文件路径:{}", bucket, objectName);
                return true;
            }
        } catch (Exception e) {
            log.error("下载文件失败,桶:{},文件路径:{}", bucket, objectName);
        }
        return false;
    }

    /**
     * 将文件信息存入数据库
     *
     * @param uploadFileParamsDto
     * @param companyId
     * @param bucket
     * @param md5Str
     * @param objectName
     * @return
     */
    @Override
    @Transactional
    public MediaFiles AddMediaFileInfo(UploadFileParamsDto uploadFileParamsDto, Long companyId, String bucket, String md5Str, String objectName) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(md5Str);
        if (mediaFiles == null) {
            //构建mediaFile对象
            mediaFiles = new MediaFiles();
            BeanUtil.copyProperties(uploadFileParamsDto, mediaFiles);
            mediaFiles.setFileId(md5Str);
            mediaFiles.setId(md5Str);
            mediaFiles.setBucket(bucket);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setCompanyId(companyId);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setUrl("/" + bucket + "/" + objectName);
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setStatus("1");
            int insert = mediaFilesMapper.insert(mediaFiles);
            if (insert <= 0) {
                XueChengPlusException.cast("保存文件信息到数据库失败");
            } else {
                log.info("保存成功,参数为:{}", mediaFiles);
            }

            //更新文件上传到minio完成情况
            updateMediaStatus(md5Str);

            //添加到待处理任务表
            addWaitingTask(mediaFiles);
        }
        return mediaFiles;
    }

    /**
     * 更新更新文件上传到minio完成情况
     *
     * @param md5Str
     */
    private void updateMediaStatus(String md5Str) {
        UpdateWrapper<MediaStatus> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", md5Str)
                .set("status", 1)
                .set("finish_time", LocalDateTime.now());
        int update = mediaStatusMapper.update(null, updateWrapper);
        if (update < 0) {
            log.error("更新文件上传到minio完成情况失败,更新对象id为:{}", md5Str);
        }
    }

    /**
     * 添加待处理任务表
     *
     * @param mediaFiles
     */
    private void addWaitingTask(MediaFiles mediaFiles) {

        //文件名称
        String filename = mediaFiles.getFilename();
        //文件扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //文件mimeType
        String mimeType = getFileType(extension);
        //如果是avi视频添加到视频待处理表
        if (mimeType.equals("video/x-msvideo")) {
            MediaProcess mediaProcess = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles, mediaProcess);
            mediaProcess.setStatus("1");//未处理
            mediaProcess.setFailCount(0);//失败次数默认为0
            int insert = mediaProcessMapper.insert(mediaProcess);
            if (insert < 0) {
                log.error("添加任务处理表失败,文件id为{},桶为:{},文件路径为:{}", mediaFiles.getFileId(), mediaFiles.getBucket(), mediaFiles.getFilePath());
            }
        }
    }

    /**
     * 检查文件是否存在
     *
     * @param fileMd5
     * @return
     */
    @Override
    public RestResponse<Boolean> checkfile(String fileMd5) {
        //首先要查数据库,看看有没有
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);

        //如果文件存在,在查minio
        if (mediaFiles != null) {
            //获取查询参数
            String bucket = mediaFiles.getBucket();
            String filePath = mediaFiles.getFilePath();

            //查询minio,以及校验文件完整性
            boolean b = this.downloadFile(bucket, fileMd5, filePath);
            if (b) {
                return RestResponse.success(true);
            }
            return RestResponse.success(false);
        }
        return RestResponse.success(false);
    }

    /**
     * 检测分块是否存在
     *
     * @param fileMd5
     * @param chunk
     * @return
     */
    @Override
    public RestResponse<Boolean> checkchunk(String fileMd5, int chunk) {
        //获取分块的目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //获取分块文件路径
        String chunkFilePath = chunkFileFolderPath + chunk;
        //查询文件在不在
        //拼接参数
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(videofiles)
                .object(chunkFilePath)
                .build();
        try (GetObjectResponse response = minioClient.getObject(getObjectArgs);) {
            if (response != null) {
                //存在返回true
                return RestResponse.success(true);
            }
        } catch (Exception e) {
        }

        return RestResponse.success(false);
    }

    /**
     * 上传分块文件
     *
     * @param fileMd5
     * @param chunk
     * @param localChunkFilePath
     * @return
     */
    @Override
    public RestResponse<Boolean> uploadchunk(String fileMd5, int chunk, String localChunkFilePath) {
        //获取分块文件目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //获取分块文件路径
        String chunkFilePath = chunkFileFolderPath + chunk;
        //获取文件类型
        String fileType = getFileType(null);

        //上传文件
        boolean b = addMediaFilesToMinIO(videofiles, localChunkFilePath, fileType, chunkFilePath);
        if (b) {
            //对上传状态信息进行记录
            if (chunk == 0) {
                MediaStatus mediaStatus = new MediaStatus();
                mediaStatus.setId(fileMd5);
                mediaStatus.setStatus(0);
                mediaStatus.setBucket(videofiles);
                mediaStatus.setFileId(fileMd5);
                mediaStatus.setUploadTime(LocalDateTime.now());
                mediaStatus.setFilePath(chunkFileFolderPath);
                //先查询,如果存在就将状态设置为正在上传
                MediaStatus mediaStatus1 = mediaStatusMapper.selectById(fileMd5);
                if (mediaStatus1 != null) {
                    mediaStatusMapper.updateById(mediaStatus);
                } else {
                    int insert = mediaStatusMapper.insert(mediaStatus);
                    if (insert <= 0) {
                        log.error("信息入库失败,参数为{}", mediaStatus);
                    }
                }
            }

            log.info("上传分块文件成功,chunkFilePath:{}", chunkFilePath);
            return RestResponse.success(true);
        }
        return RestResponse.validfail(false, "上传分块文件失败");
    }

    /**
     * 合并文件
     *
     * @param companyId
     * @param fileMd5
     * @param chunkTotal
     * @param uploadFileParamsDto
     * @return
     */
    @Override
    public RestResponse<Boolean> mergechunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
        //获取分块文件目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //合并分块文件
        //获取合并文件的集合
        List<ComposeSource> composeSources = Stream.iterate(0, integer -> ++integer).limit(chunkTotal).map(integer -> ComposeSource.builder().bucket(videofiles).object(chunkFileFolderPath + integer).build()).collect(Collectors.toList());
        //获取源文件名
        String filename = uploadFileParamsDto.getFilename();
        //获取源文件的扩展名
        String extName = filename.substring(filename.lastIndexOf('.') + 1);
        //获取合并后文件的目录
        String mergeFilePath = getMergeFilePath(fileMd5, extName);

        ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder()
                .bucket(videofiles)
                .sources(composeSources)
                .object(mergeFilePath)
                .build();
        try {
            ObjectWriteResponse objectWriteResponse = minioClient.composeObject(composeObjectArgs);

        } catch (Exception e) {
            log.error("合并文件失败,桶:{},文件路径:{}", videofiles, mergeFilePath);
            return RestResponse.validfail(false, "合并文件失败");
        }

        //验证文件的完整性
        File file = downloadFileFromMinIO(videofiles, mergeFilePath);
        if (file == null) {
            //如果文件为空,直接返回
            return RestResponse.validfail(false, "下载文件失败");
        }
        //设置文件长度
        uploadFileParamsDto.setFileSize(file.length());
        //校验文件
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String md5Hex = DigestUtils.md5Hex(fileInputStream);
            if (!fileMd5.equals(md5Hex)) {
                return RestResponse.validfail(false, "文件校验失败");
            }
        } catch (Exception e) {
            return RestResponse.validfail(false, "文件校验失败");
        } finally {
            if (file != null) {
                //删除临时文件
                file.delete();
            }
        }

        //信息入库
        mediaFileService.AddMediaFileInfo(uploadFileParamsDto, companyId, videofiles, fileMd5, mergeFilePath);

        //清理分块文件
        clearChunkFiles(chunkFileFolderPath, chunkTotal);

        return RestResponse.success(true);
    }

    /**
     * 清理分块文件
     *
     * @param chunkFileFolderPath
     * @param chunkTotal
     */
    private void clearChunkFiles(String chunkFileFolderPath, int chunkTotal) {
        List<DeleteObject> deleteObjects = Stream.iterate(0, integer -> ++integer).limit(chunkTotal).map(integer -> new DeleteObject(chunkFileFolderPath + integer)).collect(Collectors.toList());
        RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder()
                .bucket(videofiles)
                .objects(deleteObjects)
                .build();
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
        results.forEach(item -> {
            DeleteError deleteError = null;
            try {
                deleteError = item.get();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除分块文件失败,桶:{},文件路径:{},错误信息:{}", videofiles, deleteError.objectName(), e.getMessage());
            }
        });
    }

    /**
     * 获取合并后的文件目录
     *
     * @param fileMd5
     * @param extName
     * @return
     */
    private String getMergeFilePath(String fileMd5, String extName) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 + "." + extName;

    }

    /**
     * 获取分块目录
     *
     * @param fileMd5
     * @return
     */
    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/chunk/";
    }

    /**
     * 上传文件
     *
     * @param bucket
     * @param localFilePath
     * @param mimeType
     * @param objectName
     * @return
     */
    @Override
    public boolean addMediaFilesToMinIO(String bucket, String localFilePath, String mimeType, String objectName) {
        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .filename(localFilePath)
                    .object(objectName)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(uploadObjectArgs);
            return true;
        } catch (Exception e) {
            log.info("上传文件失败,参数为bucket:{},localFilePath:{},mimeType:{},objectName:{}", bucket, localFilePath, mimeType, objectName);
            XueChengPlusException.cast("上传文件失败");
        }
        return false;
    }

    /**
     * 根据id查询媒资
     *
     * @param mediaId
     * @return
     */
    @Override
    public MediaFiles getFileById(String mediaId) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(mediaId);
        if (mediaFiles == null) {
            XueChengPlusException.cast("未查询到视频信息");
        }
        return mediaFiles;
    }

    /**
     * 从minio下载文件
     *
     * @param bucket     桶
     * @param objectName 对象名称
     * @return 下载后的文件
     */
    @Override
    public File downloadFileFromMinIO(String bucket, String objectName) {
        //临时文件
        File minioFile = null;
        //创建临时文件
        try {
            minioFile = File.createTempFile("minio", ".merge");
        } catch (IOException e) {
            return null;
        }

        //组装下载参数
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucket)
                .object(objectName)
                .build();
        //下载,数据拷贝
        try (GetObjectResponse response = minioClient.getObject(getObjectArgs); FileOutputStream outputStream = new FileOutputStream(minioFile);) {
            IOUtils.copy(response, outputStream);
            return minioFile;
        } catch (Exception e) {
            log.error("下载文件失败,桶:{},文件路径:{}",bucket,objectName);
        }
        return null;
    }

    /**
     * 生成objectName
     *
     * @param md5Str
     * @return
     */
    private String getObjectName(String md5Str, String extension) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String objectName = sdf.format(new Date()).replace('-', '/') + "/" + md5Str + "." + extension;
        return objectName;
    }

    /**
     * 获取md5
     *
     * @param localFilePath
     * @return
     */
    private String getMd5Str(String localFilePath) {
        String s = null;
        try (FileInputStream fileInputStream = new FileInputStream(new File(localFilePath));) {
            s = DigestUtil.md5Hex(fileInputStream);
        } catch (IOException e) {
            XueChengPlusException.cast("获取md5失败");
        }
        return s;
    }

    /**
     * 获取文件类型
     *
     * @param extension
     * @return
     */
    private String getFileType(String extension) {
        if (extension == null) {
            extension = "";
        }
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        //通用mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;//这是为了没有后缀的文件使用的
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }
}
